package controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.ResourceBundle;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Keyword;
import model.KeywordUnique;
import server.Get;
import server.GetBing;
import server.GetContent;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

@SuppressWarnings("serial")
public class KeywordServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setCharacterEncoding("utf-8");
		String path = ((HttpServletRequest)req).getRequestURI();
		String domain = req.getParameter("domain");
		StringTokenizer st = new StringTokenizer( path,"/");
        int count = st.countTokens(); 
        
        if(count!=2)
        {
        	
        	resp.getWriter().println("Bad request : "+req.getRequestURI());
        	resp.getWriter().close();
        	return ;
        	
        }

		st.nextToken();
		String str = st.nextToken();
		str = URLDecoder.decode(str,"UTF-8");
		str = str.replaceAll("[ ]+", "+");

		PutCache.putCacheList(str, "view",30);
		
		try {
			ObjectifyService.register(Keyword.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		Objectify objectify = ObjectifyService.begin();
		
		resp.setHeader( "Cache-Control", "public, max-age=86400");
		resp.setHeader( "Expires", new Date(Calendar.getInstance().getTime().getTime()+24*60*60*1000).toGMTString());
		
		Query<Keyword> arkeyword = objectify.query(Keyword.class).filter("name", str);
		
		req.setAttribute("keywords", arkeyword);
		if(arkeyword.count()<=0) {
			String google = "";
			String title = "";
			
			ResourceBundle resource = ResourceBundle.getBundle("google");
			Enumeration bundleKeys = resource.getKeys();
	
			while (bundleKeys.hasMoreElements()) {
			    String key = (String)bundleKeys.nextElement();
			    google += key+" ";
			    
			    title += resource.getString(key)+"|";
			}
			google = google.trim();
			title = title.trim().replaceAll("[\\|]+$", "");
			
			String[] arrGoogle = google.split(" ");
			String[] arrTitle = title.split("\\|");
			
			HashMap<String,String> listGoogle = new HashMap<String,String>();
			
			for (int i = 0; i < arrTitle.length; i++) {
				listGoogle.put(arrTitle[i], arrGoogle[i]);
			}

			String[] arr = new String[listGoogle.size()];
			
			new Get(str,listGoogle,arr);

			
			try {
				Thread.sleep(1500);
			} catch (InterruptedException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
//			for (int i = 0; i < arr.length; i++) {
//				System.out.println(arr[i]);
//			}
			req.setAttribute("arr", arr);
			req.setAttribute("listGoogle", listGoogle);
			
		}
		req.setAttribute("domain", domain);
		req.setAttribute("keyword", str);
		
		try {
			ObjectifyService.register(KeywordUnique.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		Objectify objectify1 = ObjectifyService.begin();
		try {
			KeywordUnique keyword = objectify1.get(new Key<KeywordUnique>(KeywordUnique.class, str));
		} catch (Exception e) {
			KeywordUnique key = new KeywordUnique();
			key.setName(str);
			
			objectify1.put(key);
		}
		try {
			req.getRequestDispatcher("/keyword.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
}
